package servlets.user;

import hibernate.method.UserMethods;
import hibernate.util.HibernateUtil;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import external.EmailUtility;
import external.TokenGenerator;

/**
 * Servlet implementation class Add
 */
@WebServlet(name = "AddUser", urlPatterns = { "/AddUser" })

@MultipartConfig(maxFileSize = 16177215)
public class Add extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String host;
	private String port;
	private String user;
	private String pass;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Add() {
        super();
    }

    public void init() {
		// reads SMTP server setting from web.xml file
		ServletContext context = getServletContext();
		host = context.getInitParameter("host");
		port = context.getInitParameter("port");
		user = context.getInitParameter("user");
		pass = context.getInitParameter("pass");
	}
    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			String parameter = request.getParameter("parameter");
			String val = request.getParameter("val");
		//	String type = request.getParameter("type");
			
			System.out.println(parameter);
			SessionFactory sessionFactory = HibernateUtil.getSessionAnnotationFactory();
			Session s= sessionFactory.openSession();
			s.beginTransaction();
			UserMethods um = new UserMethods();

			response.setContentType("text/xml");
			response.setHeader("Cache-Control", "no-cache");

			PrintWriter out = response.getWriter();

			if ("username".equals(parameter)){
				System.out.println(um.isUsernameExist(sessionFactory, s, val));
				if (um.isUsernameExist(sessionFactory, s, val) == true || "".equals(val.trim())){
				out.println("<valid>false</valid>");
				} else {
					out.println("<valid>true</valid>");
				}
			}
			
//			if ("email".equals(parameter)){
//				System.out.println(um.isEmailExist(sessionFactory, s, val, type));
//				if (um.isEmailExist(sessionFactory, s, val, type) == true || "".equals(val.trim())){
//				out.println("<valid>true</valid>");
//				} else {
//					out.println("<valid>false</valid>");
//				}
//			}
			s.getTransaction().commit();

		} catch (Exception e ){
			e.printStackTrace();
		}
	}


	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String surname;
		String phone;
		PrintWriter out = response.getWriter();
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		SessionFactory sessionFactory = HibernateUtil
				.getSessionAnnotationFactory();
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		String username = (String) request.getParameter("username");
		String password = (String) request.getParameter("password");
		String birthdate = (String) request.getParameter("birth_date");
		String email = (String) request.getParameter("email");
		String gender= (String) request.getParameter("gender");
		String type = (String) request.getParameter("type");
		String name =  (String) request.getParameter("name");
		if ((String) request.getParameter("name") == "") name = null;
		else name = (String) request.getParameter("name");
		if ((String) request.getParameter("surname") == "") surname = null;
		else surname = (String) request.getParameter("surname");
		if((String) request.getParameter("phone") == "") phone = null;
		else phone = (String) request.getParameter("phone");
		InputStream inputStream = null;	// input stream of the upload file
		
		try {
			String dbURL = "jdbc:mysql://localhost:3306/thesis";
			String dbUser = "root";
			String dbPass = "";

			Connection conn = null;	
			DriverManager.registerDriver(new com.mysql.jdbc.Driver());
			conn = DriverManager.getConnection(dbURL, dbUser, dbPass);
			
			
		
		Part filePart = request.getPart("avatar");
		if (filePart != null) {
			// prints out some information for debugging
			System.out.println(filePart.getName());
			System.out.println(filePart.getSize());
			System.out.println(filePart.getContentType());
			
			// obtains input stream of the upload file
			inputStream = filePart.getInputStream();
		}
		
		
		response.setContentType("text/html");

		
		UserMethods user_m = new UserMethods();
		user_m.add(sessionFactory, session, username, birthdate, email, type, gender, name, surname, phone, password);
		
		
		


		if (inputStream  !=null ){
			String sql = "INSERT INTO usersavatars (user_id, avatar) values (?, ?)";
			PreparedStatement statement = conn.prepareStatement(sql);
			statement.setLong(1, user_m.is_user(sessionFactory, session, username).get(0).getUser_id());
			statement.setBlob(2, inputStream);
			statement.executeUpdate();
		}
		
		if (filePart.getSize()==0) {
		 inputStream = new FileInputStream("M://Thesis/Thesis/src/servlets/user/avatar.png");
		String sql = "INSERT INTO usersavatars (user_id, avatar) values (?, ?)";
		PreparedStatement statement = conn.prepareStatement(sql);
		statement.setLong(1, user_m.is_user(sessionFactory, session, username).get(0).getUser_id());
		statement.setBlob(2, inputStream);
		statement.executeUpdate();
		
		
			
		}
		
		if(type =="client") {
		String token = TokenGenerator.generateToken();
		user_m.insertToken(sessionFactory, session, token, "activate", user_m.is_user(sessionFactory, session, username).get(0).getUser_id(), email);
		String tresc = EmailUtility.sendActivationMail(TokenGenerator.linkWithToken(token, "activate", user_m.is_user(sessionFactory, session, username).get(0).getUser_id()), user_m.is_user(sessionFactory, session, username).get(0).getUsername());
		
		
		
		EmailUtility.sendEmail(host, port, user, pass, email, "[HexGames Social] Link aktywacyjny", tresc);
		
		
		session.getTransaction().commit();
		out.println("<script type=\"text/javascript\">alert(\"Na podany adres email wyslalismy wiadomosc z linkiem aktywacyjnym\"); window.location.href = \"social/index.jsp?page=main\";</script>");
		}
		else 
		{
			user_m.activateUser(sessionFactory, session, user_m.is_user(sessionFactory, session, username).get(0).getUser_id());
			session.getTransaction().commit();
			out.println("<script type=\"text/javascript\">alert(\"Uzytkownik zostal utworzony. Mozna sie zalogowac\"); window.location.href = \"social/index.jsp?page=main\";</script>");
			
		}
		}
		catch (Exception e){ 
			out.println("<script type=\"text/javascript\">alert(\"Nie udalo sie dodac uzytkownika. Za utrudnienia przepraszamy\"); window.location.href = \"social/index.jsp?page=main\";</script>");
		}
		session.clear();
		session.close();
	}

}
